package main

import (
	"fmt"
	"gitee.com/baidugoogle/upload_file/help"
	"gitee.com/baidugoogle/upload_file/upload_task_new"
	"log"
	"os"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"gitee.com/baidugoogle/upload_file/upload_task"
	"gitee.com/baidugoogle/upload_file/upload_task/structs"
)

func init() {
	log.SetFlags(log.Lmicroseconds | log.Lshortfile)

	log.SetOutput(help.NewCustomLogout(os.Stdout))
}

var config = help.NewJsonConfig()

func main() {
	if !config.Load() {
		return
	}

	for i := 0; i < config.LoopCount; i++ {
		log.Printf("\n\n==================开始第 [%v] 次循环上传==================", i+1)
		time.Sleep(time.Second)

		uploadTaskList(config.Filename, config.TaskCount)

		time.Sleep(time.Second * 3)
	}
}

var charIndex atomic.Uint32

func getChar() string {
	const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

	index := charIndex.Load()
	charIndex.Add(1)

	i := int(index) % len(chars)
	return string(chars[i])
}

func uploadTaskList(filename string, taskCount int) {
	var uploadTask = func(filename string) string {
		puId := fmt.Sprintf("PU_%v", time.Now().Format("0102150405"))

		now := time.Now()
		var info = &structs.JsonCreateExt{
			FileId:    "",
			PuId:      puId,
			UserId:    "admin",
			BeginTime: now.Unix(),
			EndTime:   now.Add(time.Hour).Unix(),
			Channel:   0,
			FileType:  "video",
			Lat:       0,
			Lng:       0,
			Desc1:     "",
			Desc2:     "",
			Mark:      false,
		}

		task := upload_task_new.NewTask(config.URI, config.GetToken)

		if uploadID, err := task.Upload(filename, info, config.OneTaskThread); err != nil {
			log.Printf("upload fail. %v, upload ID: %v, [%v]", err, uploadID, filename)
			_, _ = task.HttpCancel(uploadID)
			return err.Error() + time.Since(now).String()
		} else {
			log.Printf("upload success. %v [%v]", uploadID, filename)
			return "success " + time.Since(now).String()
		}
	}

	var result = map[string]string{}

	var wg sync.WaitGroup
	for i := 0; i < taskCount; i++ {

		wg.Add(1)
		go func() {
			defer wg.Done()

			dstFilename := fmt.Sprintf("%v_%v.mp4", time.Now().Format("01月02日_150405"), getChar())
			if err := help.CopyFile(dstFilename, filename); err != nil {
				log.Println(err)
				return
			}

			defer os.Remove(dstFilename)

			msg := uploadTask(dstFilename)
			result[dstFilename] = msg
		}()

		time.Sleep(time.Second)
	}

	wg.Wait()

	success := 0
	for k, v := range result {
		if strings.HasPrefix(v, "success") {
			success++
		}
		log.Printf("---> %v %v", k, v)
	}

	log.Printf("成功: %v, 总数: %v", success, taskCount)
}

func example() {
	var info = &structs.JsonCreateExt{
		FileId:    "",
		PuId:      "PU_222",
		UserId:    "admin",
		BeginTime: 1689215796,
		EndTime:   1689215796,
		Channel:   0,
		FileType:  "video",
		Lat:       0,
		Lng:       0,
		Desc1:     "",
		Desc2:     "",
		Mark:      false,
	}

	task := upload_task.NewUploadTask(config.URI, config.GetToken)

	if len(config.ResumeUploadId) > 0 {
		if err := task.ResumeUpload(config.Filename, config.ResumeUploadId); err != nil {
			log.Printf("resume upload fail. %v", err)
		} else {
			log.Printf("resume upload success")
		}
	} else {
		if uploadID, err := task.Upload(config.Filename, info); err != nil {
			log.Printf("upload fail. %v, upload ID: %v", err, uploadID)
		} else {
			log.Printf("upload success. %v", uploadID)
		}
	}
}
